/**
 * Copyright (c) 2018-present, Chen Guodong
 * All rights reserved.
 *
 * @flow
 */


<template>
  <div class="content">
    <ul class="box">
      <li class="finish" v-for="item in fileInfo" :key="item.id" v-longTouch="()=>handleLongTouch(item.id)">

        <img :src="getImageSrc(item)" :alt="item.name">
        <p class="name">{{item.name}}</p>
        <!-- <p class="tip error" v-show="item.status === 2">上传失败</p>
        <p class="tip success" v-show="item.status === 1">上传成功</p> -->
        <p class="progressBox" v-show="item.percentage && item.percentage != 100">
          <mt-progress :value="item.percentage">
          </mt-progress>
        </p>
        
      </li>
      <!-- 上传按钮组件样式在static/css/config.css中修改 -->
      <li class="default" id="picker"></li>
    </ul>
  </div>
</template>

<script>
import { Actionsheet, Progress, Toast, MessageBox, Indicator } from "mint-ui";
import { delItemByKey, getIndex } from "../../util/util.js";

export default {
  props: {
    changeUpdateFileIds: Function,
  },
  data() {
    return {
      fileInfo: [],
      sheetVisible: false,
      selectedFileId: "",
      updateSuccessFile: [],
      filesData: [],
    };
  },
  watch: {
    // updateSuccessFile: function(data){
    //   console.log("updateSuccessFile", data)
    //   this.changeUpdateFileIds(data);
    // },
    filesData: function(data){
      this.changeUpdateFileIds(data)
    }
  },
  methods: {
    initWebUpload() {
      const self = this;
      const loginInfo = JSON.parse(localStorage.getItem("loginInfo"));

      var uploader = WebUploader.create({
        // swf文件路径
        swf: "../../../static/js/webuploader-0.1.5/Uploader.swf",

        // 文件接收服务端。
        server: "http://192.168.1.204:80/public/api/upload/index",
        // 自动上传
        auto: true,

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: {
          id: "#picker",
          innerHTML:
            '<i class="iconfont icon-jia"></i>'
        },
        formData:{
          token: loginInfo ? loginInfo.token : ''
        },

        // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
        resize: false,
        duplicate: true // 重复上传
      });
      self.uploader = uploader;
      // 当有文件被添加进队列的时候，添加到页面预览
      self.uploader.on("fileQueued", file => {
        uploader.makeThumb(file, function(error, src) {
          file.src = src;
          self.fileInfo.push(file);
          Indicator.open({
            text: "上传中...",
            spinnerType: "fading-circle"
          });
        });
      });
      // 文件上传过程中创建进度条实时显示。
      uploader.on("uploadProgress", function(file, percentage) {
        console.log("上传进度", percentage * 100 + "%");
        var index = getIndex(self.fileInfo, file.id);
        self.$set(self.fileInfo[index], "percentage", percentage * 100);
      });
      // 文件上传成功，给item添加成功class, 用样式标记上传成功。
      uploader.on("uploadSuccess", function(file, response) {
        //status 1 上传成功
        var index = getIndex(self.fileInfo, file.id);
        self.$set(self.fileInfo[index], "status", 1);
        console.log("response", response)
        if(response.code === 1){
          self.$set(self.fileInfo[index], "response", response.data);
          self.updateSuccessFile.push(response.data.fileId);
          self.filesData.push({fileId: response.data.fileId, title: response.data.title, path: response.data.path, })
        }
        console.log("上传成功!", file);
      });
      // 文件上传失败，显示上传出错。
      uploader.on("uploadError", function(file) {
        //status 2 上传失败
        var index = getIndex(self.fileInfo, file.id);
        self.$set(self.fileInfo[index], "status", 2);
        self.fileInfo.splice(index, 1);
        Toast("上传失败!");
      });
      // 完成上传完了，成功或者失败，先删除进度条。
      uploader.on("uploadComplete", function(file) {
        var index = getIndex(self.fileInfo, file.id);
        Indicator.close();
      });
    },
    delFile() {
      // debugger;
      var self = this;
      const delingFile = self.fileInfo.filter(item => item.id === self.selectedFileId)[0].fileId;
      this.updateSuccessFile.splice(this.updateSuccessFile.indexOf(delingFile), 1);
      this.filesData.splice(this.filesData.map(item=>item.fileId).indexOf(delingFile), 1)
      this.fileInfo = delItemByKey(self.fileInfo, self.selectedFileId);

    },
    // 生成预览图片src
    getImageSrc(item) {
      if (item.src) {
        return item.src;
      } else {
        return "../../../static/img/word.jpg";
      }
    },
    // 长按文件
    handleLongTouch(id) {
      this.selectedFileId = id;
      MessageBox.confirm("确定删除文件?").then(action => {
        if (action === "confirm") {
          this.delFile();
        }
      });
    }
  },
  mounted() {
    this.initWebUpload();
  },
  components: {
    "mt-actionsheet": Actionsheet,
    "mt-progress": Progress
  }
};
</script>

<style lang='less' scoped>
@import "../../util/themt.less";

.content {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background: #fff;
  position: relative;
  padding: 0 10px;
  .box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    box-sizing: border-box;
    flex-wrap: wrap;
    font-size: 0;
    position: relative;
    li {
      // width: calc(~"25% - 5px");
      // // width: 23%;
      // height: 20vw;
      width: 50px;
      height: 50px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border: 1px solid @gray;
      box-sizing: border-box;
      margin-right: 5px;
      margin-bottom: 5px;
      border-radius: 8px;
      position: relative;
      overflow: hidden;
      img {
        width: 100%;
        max-width: 100%;
        max-height: 100%;
      }
      .name {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        background: rgba(0, 0, 0, 0.8);
        color: #fff;
        z-index: 99;
        text-align: center;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        line-height: 20px;
      }
      .tip,
      .progressBox {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        color: #fff;
        text-align: center;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        line-height: 20px;
        z-index: 99;
      }
      .progressBox {
        width: 100%;
        line-height: 100%;
        height: 100%;
        line-height: 20px;
        vertical-align: middle;
        background: rgba(0, 0, 0, 0.8);
        padding: 0 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        .mt-progress {
          flex: 1;
        }
      }
      .error {
        background: red;
      }
      .success {
        background: green;
      }
    }
  }
}

.default {
  color: @gray;
  i {
    font-size: 42px;
  }
  p {
    font-size: 13px;
    line-height: 20px;
  }
}
</style>
